import { createStore, combineReducers, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
import { cartReducer } from './cart'
import { userReducer } from './user'
import { typeCartItem, typeAddress } from '../types/cart'

const reducer = combineReducers({
  cart: cartReducer,
  user: userReducer,
})

/* 获取初始购物车信息 */
const cartStore:string|null = localStorage.getItem('cartItems')
const cartItemsFromStorage:typeCartItem[] = cartStore ? JSON.parse(cartStore) : []
/* 获取初始地址信息 */
const addressStore:string|null = localStorage.getItem('address')
const addressFromStorage:typeAddress = addressStore ? JSON.parse(addressStore) : null

const initialState:any = {
  cart: {
    cartItems: cartItemsFromStorage,
    address: addressFromStorage,
    payment: 'wx'
  },
}

const middleware = [thunk]

const store = createStore(
  reducer,
  initialState,
  composeWithDevTools(applyMiddleware(...middleware))
)

export default store
